<template>
  <div v-loading="loading" class="app-content">
    <!-- 头部区域 -->
    <div class="text-center mb-12">
      <div class="inline-block rounded-full mb-1" style="background-color: var(--el-bg-color)">
        <img src="@/assets/logo.png" alt="Logo" class="w-20 h-20" />
      </div>
      <h1 class="text-3xl font-bold mb-2" style="color: var(--el-text-color-primary)">多客怪兽</h1>
      <p class="text-lg mb-4" style="color: var(--el-text-color-regular)">系统版本管理</p>

      <!-- 当前版本信息 -->
      <div
        class="inline-flex items-center gap-4 p-4 rounded-lg border"
        style="background-color: var(--el-bg-color); border-color: var(--el-border-color-light)"
      >
        <el-icon class="text-2xl" style="color: var(--el-color-primary)"><Box /></el-icon>
        <div class="text-sm" style="color: var(--el-text-color-regular)">当前版本</div>
        <div class="text-xl font-bold" style="color: var(--el-color-primary)">v{{ version.version || '1.0.0' }}</div>
        <el-button type="primary" size="small" :loading="loading" @click="onGetUpdateMsg">
          <el-icon><Refresh /></el-icon>
          检查更新
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="max-w-4xl mx-auto">
      <!-- 有更新时显示 -->
      <div v-if="!loading && list.length > 0">
        <!-- 最新版本提示 -->
        <div
          class="mb-8 p-6 rounded-lg border"
          style="background-color: var(--el-color-warning-light-9); border-color: var(--el-color-warning-light-7)"
        >
          <div class="flex items-center justify-between">
            <div class="flex items-center gap-4">
              <el-icon class="text-3xl" style="color: var(--el-color-warning)"><Warning /></el-icon>
              <div>
                <h3 class="text-lg font-semibold mb-1" style="color: var(--el-text-color-primary)">发现新版本</h3>
                <p class="text-sm" style="color: var(--el-text-color-regular)">
                  最新版本 <strong>{{ version.new_version?.version }}</strong> 已发布，建议及时更新
                </p>
              </div>
            </div>
            <el-button type="warning" size="large" @click="onHandleUpdate">
              <el-icon><Download /></el-icon>
              立即更新
            </el-button>
          </div>
        </div>

        <!-- 更新日志 -->
        <div
          class="p-6 rounded-lg shadow-sm border"
          style="background-color: var(--el-bg-color); border-color: var(--el-border-color-light)"
        >
          <h3 class="text-lg font-semibold mb-6 flex items-center" style="color: var(--el-text-color-primary)">
            <el-icon class="mr-2" style="color: var(--el-color-primary)"><Document /></el-icon>
            更新日志
          </h3>

          <el-timeline class="update-timeline">
            <el-timeline-item
              v-for="(item, index) in list"
              :key="item.id"
              :timestamp="item.timestamp"
              placement="top"
              :type="index === 0 ? 'primary' : 'info'"
              :size="index === 0 ? 'large' : 'normal'"
            >
              <div
                class="p-6 rounded-lg border transition-all hover:shadow-md"
                :style="
                  index === 0
                    ? 'background-color: var(--el-color-primary-light-9); border-color: var(--el-color-primary-light-7)'
                    : 'background-color: var(--el-bg-color); border-color: var(--el-border-color-light)'
                "
              >
                <!-- 版本头部 -->
                <div class="flex items-center justify-between mb-4">
                  <div class="flex items-center gap-3">
                    <el-tag :type="index === 0 ? 'primary' : 'info'" size="large">
                      {{ item.version_detailed }}
                    </el-tag>
                    <el-tag v-if="index === 0" type="warning" size="small">最新版本</el-tag>
                  </div>
                </div>

                <!-- 更新内容 -->
                <div class="update-content text-left" style="color: var(--el-text-color-primary)" v-html="item.update_content"></div>

                <!-- 版本信息 -->
                <div
                  class="mt-4 pt-4 border-t flex justify-between items-center text-sm"
                  style="border-color: var(--el-border-color-lighter); color: var(--el-text-color-regular)"
                >
                  <span>从 v{{ item.old_version }} 升级到 v{{ item.version }}</span>
                  <span>发布时间: {{ item.create_time }}</span>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <!-- 无更新时显示 -->
      <div v-else-if="!loading" class="text-center py-16">
        <div class="inline-block rounded-full mb-6">
          <el-icon class="text-6xl" style="color: var(--el-color-success)" :size="80"><CircleCheck /></el-icon>
        </div>
        <h3 class="text-2xl font-semibold mb-4" style="color: var(--el-text-color-primary)">系统已是最新版本</h3>
        <p class="text-lg mb-6" style="color: var(--el-text-color-regular)">当前版本 v{{ version.version }} 是最新版本，无需更新</p>
        <!-- <el-button type="primary" :loading="loading" @click="onGetUpdateMsg">
          <el-icon><Refresh /></el-icon>
          重新检查
        </el-button> -->
      </div>
    </div>

    <!-- 更新进度对话框 -->
    <el-dialog
      v-model="dialogUpdateVisible"
      title="系统更新中"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="500px"
      class="update-dialog"
    >
      <div class="text-center py-6">
        <div class="mb-6">
          <img src="@/assets/default/upgrade.gif" alt="更新中" class="w-24 h-24 mx-auto" />
        </div>

        <div class="mb-6">
          <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" :color="percentageColors" class="mb-4" />
          <p class="text-lg font-medium" style="color: var(--el-text-color-primary)">{{ updateText }}</p>
        </div>

        <div class="text-sm" style="color: var(--el-text-color-regular)">
          <p>更新过程中请勿关闭页面</p>
          <p>更新完成后请强制刷新页面</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, defineOptions } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Box, Refresh, Warning, Download, Document, CircleCheck } from '@element-plus/icons-vue'
import { getUpdateMsg, upgrade } from '@/api/cloud/cloud'

defineOptions({
  name: 'CloudUpgrade'
})

// 响应式数据
const version = ref({})
const list = ref([])
const loading = ref(true)
const dialogUpdateVisible = ref(false)
const percentage = ref(1)
const percentageColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]
const updateText = ref('系统升级中...')
let interval = null

// 生命周期
onMounted(() => {
  onGetUpdateMsg()
})

// 获取更新信息
function onGetUpdateMsg() {
  loading.value = true
  getUpdateMsg()
    .then((res) => {
      version.value = res.data.version
      list.value = res.data.list.reverse()
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// 处理更新按钮点击
function onHandleUpdate() {
  ElMessageBox.confirm('是否确定要更新到最新版本？更新前请提前备份重要数据！', '系统更新确认', {
    confirmButtonText: '确定更新',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true,
    message: `
        <div style="margin: 16px 0;">
          <p><strong>更新信息：</strong></p>
          <p>当前版本：v${version.value.version}</p>
          <p>目标版本：v${version.value.new_version?.version}</p>
          <p style="color: #e6a23c; margin-top: 12px;">
            <i class="el-icon-warning"></i>
            更新过程中请勿关闭页面或刷新浏览器
          </p>
        </div>
      `
  })
    .then(() => {
      onHandleSystemUpdate()
    })
    .catch(() => {
      ElMessage.info('已取消更新')
    })
}

// 执行系统更新
function onHandleSystemUpdate() {
  if (!list.value.length) return

  const latestVersion = list.value[list.value.length - 1]
  const size = latestVersion.file_size
  const timeout = Math.max(size / 10240, 100)

  dialogUpdateVisible.value = true
  percentage.value = 1

  interval = setInterval(() => {
    if (percentage.value >= 100) {
      clearInterval(interval)
      return
    }

    if (percentage.value < 20) {
      updateText.value = `正在下载更新包 (${formatFileSize(size)})，请耐心等待...`
      percentage.value += 2
    } else if (percentage.value >= 98) {
      percentage.value = 99
      updateText.value = '正在完成更新，如果长时间未响应请刷新重试或联系技术支持'
    } else {
      updateText.value = '正在解压安装，更新完成后请强制刷新页面！'
      percentage.value++
    }
  }, timeout)

  upgrade()
    .then((res) => {
      clearInterval(interval)
      percentage.value = 100
      updateText.value = '更新完成！'

      setTimeout(() => {
        dialogUpdateVisible.value = false
        ElMessage.success(res.msg || '系统更新成功')
        onGetUpdateMsg(false)
      }, 2000)
    })
    .catch((error) => {
      clearInterval(interval)
      dialogUpdateVisible.value = false
      ElMessage.error(error.message || '更新失败，请重试')
    })
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes) return '0 B'

  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时间
function formatTime(timestamp) {
  if (!timestamp) return '未知'

  const date = new Date(timestamp * 1000)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped lang="scss">
// 更新内容样式
.update-content {
  :deep(p) {
    margin: 8px 0;
    line-height: 1.6;
  }

  :deep(ul),
  :deep(ol) {
    margin: 8px 0;
    padding-left: 20px;

    li {
      margin: 4px 0;
      line-height: 1.5;
    }
  }

  :deep(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 12px 0;

    th,
    td {
      border: 1px solid var(--el-border-color-light);
      padding: 8px 12px;
      text-align: left;
    }

    th {
      background-color: var(--el-fill-color-light);
      font-weight: 600;
    }
  }

  :deep(strong) {
    color: var(--el-color-primary);
    font-weight: 600;
  }

  :deep(code) {
    background-color: var(--el-fill-color-light);
    padding: 2px 6px;
    border-radius: 4px;
    font-family: 'Courier New', monospace;
    font-size: 0.9em;
  }
}

// 时间轴样式优化
.update-timeline {
  :deep(.el-timeline-item__timestamp) {
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

// 更新对话框样式
.update-dialog {
  :deep(.el-dialog__header) {
    text-align: center;
    padding: 20px 20px 10px;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  :deep(.el-dialog__body) {
    padding: 10px 20px 20px;
  }
}

// 响应式调整
@media (max-width: 768px) {
  .update-timeline {
    :deep(.el-timeline-item__timestamp) {
      font-size: 12px;
    }
  }

  .update-content {
    :deep(table) {
      font-size: 12px;

      th,
      td {
        padding: 6px 8px;
      }
    }
  }
}
</style>
